package com.ea.common.filter;





import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;

import com.ea.common.utils.HttpKit;











/**
 * Restful方式登陆<br>
 * 在参数中或者header里加参数login-token作为登陆凭证<br>
 * 参数值是登陆成功后的返回值中获取
 * 
 * @author 邢广军
 *
 *         
 */
public class RestfulFilter extends UserFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		 
		 return super.isAccessAllowed(request, response, mappedValue);
	}



	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	    String servletPath = HttpKit.getRequest().getServletPath();
		if (isLoginRequest(request, response)||servletPath.equals("/")) {
			return super.onAccessDenied(request, response);
        } else {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);
            HttpServletResponse httpServletResponse = WebUtils.toHttp(response);  
            if (isAjax(httpRequest)) {
                
               
              
                httpServletResponse.setHeader("sessionstatus", "timeout");//在响应头设置session状态
                 
                return false;
    
            } else {  
            	httpServletResponse.sendRedirect("/sessionout");  
            	return false;
            } 
            
       

        }
	}
	  /**
     * 判断ajax请求
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request){
        return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }

	

}
